import com.alibaba.fastjson2.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/req")
public class RequestServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res){
        //获取请求参数
        System.out.println(req.getMethod());
        //获取项目的虚拟路径，项目的前缀
        System.out.println(req.getContextPath());
        //获取请求的完整地址
        System.out.println(req.getRequestURL());
        //获取资源地址，去掉协议、IP、端口号后的
        System.out.println(req.getRequestURI());
        //获取地址参数
        System.out.println(req.getQueryString());
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        //获取post请求体，通过输入流获取
        res.setContentType("application/json");
        res.setCharacterEncoding("UTF-8");
        BufferedReader br = req.getReader();
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        JSONObject json = JSONObject.parseObject(sb.toString());
        System.out.println(json.get("name"));
        //json对象转javabean
        Student student = JSONObject.parseObject(sb.toString(), Student.class);
        System.out.println(student.getName());
    }
}
